package cloud.maque.gateway.config;

import cloud.maque.conf.MaqueProperties;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class GatewayConfig {

    @Autowired
    private MaqueProperties maqueProperties;

    /**
     * 白名单路径配置
     */
    public static final List<String> WHITE_LIST = new ArrayList<>();

    static {
        // 登录接口
        WHITE_LIST.add("/auth/login");
        WHITE_LIST.add("/auth/register");
        // Swagger相关
        WHITE_LIST.add("/swagger-ui.html");
        WHITE_LIST.add("/swagger-resources/**");
        WHITE_LIST.add("/webjars/**");
        WHITE_LIST.add("/*/v2/api-docs");
        WHITE_LIST.add("/v2/api-docs");
        // 健康检查
        WHITE_LIST.add("/actuator/**");
    }

    @PostConstruct
    public void init() {
        // 添加配置文件中的白名单
        WHITE_LIST.addAll(maqueProperties.getGateway().getWhiteList().getUrls());
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}
